<script setup>
import { ref, onMounted } from 'vue'
import { sessionApi, listModApi, treeModApi, sortModApi, saveModApi, delModsApi, oneModApi } from '@/common/api'
import router from '@/common/router'
import Note from '@/components/notify'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import { CScrollbar } from 'c-scrollbar'
import UbtTreeSel from '@/components/cascader/UbtTreeSel.vue'

// 自动加载，判断权限
onMounted(() => {
  checkAuth()
})

const procAuth = ref({
  addAuth: false,
  delAuth: false,
  edtAuth: false
})
// checkAuth 获取权限
const checkAuth = async () => {
  const res = await sessionApi()
  if(res.code === 200) {
    const userBtnCode = res.data.btnCodes
    procAuth.value = {
      addAuth: userBtnCode.indexOf('1001010101') !== -1,
      delAuth: userBtnCode.indexOf('1001010102') !== -1,
      edtAuth: userBtnCode.indexOf('1001010103') !== -1
    }
    list()
  } else {
    Msg({ kind: 'error', txt: res.msg })
    router.replace('/login')
  }
}

const modList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async () => {
  hasData.value = false
  const res = await listModApi()
  if(res.code === 200 && res.data) {
    hasData.value = true
    modList.value = res.data
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    modList.value.forEach(item => {
      idList.value.push(item.modId)
      checkList.value.push(true)
    })
  } else {
    modList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, modId) => {
  if(!checkList.value[idx]) {
    idList.value.push(modId)
  } else {
    let index = idList.value.findIndex(id => {
      if(id === modId){
        return true
      }
    })
    idList.value.splice(index, 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const modObj = {
  modId: '',
  modName: '',
  modCode: '',
  parentId: '',
  parentName: '',
  parentCode: '',
  sort: 0,
  modPos: '',
  url: '',
  showed: 1,
}
const modForm = ref(modObj)
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
  getModTree()
}

// 获取模块数
const treeRef = ref([])
const getModTree = async () => {
  const res = await treeModApi()
  if(res.code === 200) {
    treeRef.value = res.data
    treeRef.value.unshift({
      selId: '111111111111111111111',
      selName: '一级模块',
      selCode: '10000000',
      selPid: '000000000000000000000',
      chked: false,
      children: null
    })
  }
}

// update 修改
const update = async (modId) => {
  const res = await oneModApi({modId})
  if(res.code === 200) {
    showModal.value = true
    modForm.value = res.data
    getModTree()
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let modId = modForm.value.modId
  let modName = modForm.value.modName
  let modCode = modForm.value.modCode
  let parentId = modForm.value.parentId
  let sort = parseInt(modForm.value.sort)
  modForm.value.sort = sort
  let modPos = modForm.value.modPos
  if(modName === '' || modName.length > 50) {
    Msg({ kind: 'warn', txt: '模块的名称不能为空，且长度不超过50个字符' })
    return
  } else if(modCode === '' || modCode.length !== 8) {
    Msg({ kind: 'warn', txt: '模块的编码不能为空，且长度为8位的数字编码' })
    return
  } else if(parentId === '' || parentId.length !== 21) {
    Msg({ kind: 'warn', txt: '父级模块不能为空' })
    return
  } else if(sort < 1) {
    Msg({ kind: 'warn', txt: '模块排序不能为空' })
    return
  } else if(modPos === '') {
    Msg({ kind: 'warn', txt: '模块位置不能为空' })
    return
  } else if(modId === parentId) {
    Msg({ kind: 'warn', txt: '不可选择当前模块为父级模块' })
    return
  }
  const res = await saveModApi(modForm.value)
  if(res.code === 200) {
    closeModal()
    list()
    Note({ kind: 'success', title: '成功', txt: '恭喜您，模块信息保存成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  modForm.value = {
    modId: '',
    modName: '',
    modCode: '',
    parentId: '',
    parentName: '',
    parentCode: '',
    sort: 0,
    modPos: '',
    url: '',
    showed: 1,
  }
}

// deletes 批量删除模块
const deletes = async() => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('删除模块，会将其子模块一起删除，确定这样操作吗？').then(() => {
    delMods()
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// delMods 删除模块实现，分离出来防止调用时异步报错
const delMods = async () => {
  let modIds = idList.value.join(',')
  const res = await delModsApi({ modIds })
  if(res.code === 200) {
    list()
    Note({ kind: 'success', title: '成功', txt: '恭喜您，模块信息删除成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// setValue 为下拉框赋值
const setValue = (mod) => {
  // 调用排序接口
  sortMod(mod.selId, mod.selCode)
  modForm.value.parentId = mod.selId
  modForm.value.parentName = mod.selName
  modForm.value.parentCode = mod.selCode
}

// sortMod 模块排序
const sortMod = async (parentId, modCode) => {
  const res = await sortModApi({ parentId })
  if(res.code === 200) {
    modForm.value.sort = res.data
    // 为模块自动编码
    modForm.value.modCode = modCode.substring(0, modCode.length-2) + '0' + res.data
  }
}

// chkShowed 单选框显示隐藏效果
const chkShowed = (idx) => {
  switch(idx) {
    case 1:
      modForm.value.showed = 1
      break
    case 2:
      modForm.value.showed = 2
      break
    default:
      modForm.value.showed = 1
      break
  }
}
</script>

<template>
  <div class="a">
    <!-- 头部按钮 -->
    <div class="b">
      <div v-if="procAuth.addAuth" class="btn-p" title="新增" @click="add()"><i class="iconfont doc_text"></i> 新增</div>
      <div v-if="procAuth.delAuth" class="btn-d" title="删除" @click="deletes()"><i class="iconfont trash"></i> 删除</div>
      <div class="btn-r" title="刷新" @click="list()"><i class="iconfont arrow__circlepath"></i></div>
    </div>
    <!-- 中部数据 -->
    <div class="c" v-if="hasData">
      <table>
        <tr>
          <th style="width: 5%;"><i @click="checkAll()" :class="['iconfont', allCheck ? 'checkmark_square_fill chked' : 'app chk']"></i></th>
          <th style="width: 20%;">名称</th>
          <th style="width: 10%;">编码</th>
          <th style="width: 18%;">地址</th>
          <th style="width: 7%;">排序</th>
          <th style="width: 22%;">位置</th>
          <th style="width: 8%;">显示</th>
          <th style="width: 10%;">操作</th>
        </tr>
        <tr v-for="(curMod, index) in modList" :key="curMod.modId" class="tr-style">
          <td class="txt-center"><i @click="checkCurId(index, curMod.modId)" :class="['iconfont', checkList[index] ? 'checkmark_square_fill chked' : 'app chk']"></i></td>
          <td><div :style="{'padding-left': curMod.modLevel*15+'px'}">{{curMod.modName}}</div></td>
          <td class="txt-center">{{curMod.modCode}}</td>
          <td>{{curMod.url}}</td>
          <td class="txt-center">{{curMod.sort}}</td>
          <td>{{curMod.modPos}}</td>
          <td class="txt-center">{{curMod.showed===1 ? '显示' : '隐藏'}}</td>
          <td class="txt-center">
            <span v-if="procAuth.edtAuth" class="cl-blue" title="修改" @click="update(curMod.modId)"><i class="iconfont square_pencil"></i> 修 改</span>
          </td>
        </tr>
      </table>
    </div>
    <div v-else class="no-data">暂无内容</div>
    
    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_plaintext fs20"></i> 保存模块信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>父级模块</div>
                <ubt-tree-sel :tree-list="treeRef" :kind="1" :inboxed="false" :curName="modForm.parentName!=='' ? modForm.parentName+'['+modForm.parentCode+']' : ''" pre-name="父级模块" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>模块排序</div>
                <div><input type="text" v-model="modForm.sort" maxlength="11" placeholder="请输入模块排序" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>模块编码</div>
                <div><input type="text" v-model="modForm.modCode" maxlength="8" placeholder="请输入模块编码" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>模块名称</div>
                <div><input type="text" v-model="modForm.modName" maxlength="50" placeholder="请输入模块名称" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>模块位置</div>
                <div><input type="text" v-model="modForm.modPos" maxlength="85" placeholder="请输入模块位置" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title">模块地址</div>
                <div><input type="text" v-model="modForm.url" maxlength="60" placeholder="请输入跳转地址" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>是否显示</div>
                <div class="d">
                  <div class="cur e" @click="chkShowed(1)"><i :class="['iconfont', modForm.showed===1 ? 'largecircle_fill_circle chked' : 'circle chk']"></i> 显示</div>
                  <div class="cur e" @click="chkShowed(2)"><i :class="['iconfont', modForm.showed===1 ? 'circle chk' : 'largecircle_fill_circle chked']"></i> 隐藏</div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="save"><i class="iconfont today_fill"></i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont arrowshape_turn_up_left"></i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.a {width: 100%; height: 100%;}
.b {padding: 10px 20px; display: flex; display: -webkit-flex;}
.c {background-color: #FFF;}
.d {display: flex; display: -webkit-flex;}
.e {width: 80px; margin: 10px;}
</style>
